/**
 * https://leetcode.cn/problems/flood-fill/
 */
function floodFill(
  image: number[][],
  sr: number,
  sc: number,
  color: number
): number[][] {
  const rowLength = image.length;
  const colLength = image[0].length;
  const stack: number[][] = [[sr, sc]];
  const curColor = image[sr][sc];
  if (curColor === color) return image;
  while (stack.length > 0) {
    const [row, col] = stack.pop()!;
    if (
      row >= 0 &&
      row < rowLength &&
      col >= 0 &&
      col < colLength &&
      image[row][col] === curColor
    ) {
      // row 和 col 在合法的范围内
      image[row][col] = color;
      stack.push([row + 1, col]);
      stack.push([row - 1, col]);
      stack.push([row, col + 1]);
      stack.push([row, col - 1]);
    }
  }

  return image;
}
